package com.coding.controller;


import javax.servlet.http.HttpServletRequest;

import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

import com.coding.bean.ShiroUser;
import com.coding.constant.Constant;
import com.coding.log.LogManager;
import com.coding.log.LogTaskFactory;
import com.coding.utils.VsTools;
import com.coding.utils.MD5Util;
import com.coding.utils.Userinfo;

@Controller
public class LoginController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private VsTools vsTools;

    /**
     * 登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public String login(Model model, HttpServletRequest request, ShiroUser user) {
        if (vsTools.getKaptchaSwich()) {
            // 用户输入的验证码的值
            String kaptchaRecevied = request.getParameter("kaptcha");
            // 生成的验证码
            String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

            log.info("验证码：" + kaptchaExpected);
            log.info("用户输入的验证码：" + kaptchaRecevied);

            // 校验验证码是否正确，忽略大小写
            if (kaptchaRecevied == null || !kaptchaRecevied.equalsIgnoreCase(kaptchaExpected)) {
                model.addAttribute("msg", "验证码错误");
                model.addAttribute("status", Constant.ERROR_CODE_VERICATION_CODE_ERROR);
                return "error";// 返回验证码错误
            }
        }

        Subject subject = SecurityUtils.getSubject();
        user.setPassword(MD5Util.encrypt(user.getPassword()));

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(token);
            // shiro session过期时间12小时
            subject.getSession().setTimeout(1000 * 60 * 60 * 24);
        } catch (AuthenticationException e) {
            log.warn("登陆失败");
            model.addAttribute("status", Constant.ERROR_CODE_USERNAME_PASSWORD_MISMATCH);
            model.addAttribute("msg", "账号或密码错误");
            LogManager.getInstance().saveLog(LogTaskFactory.getLoginFailTimerTask(user.getUsername(), "账号与密码不匹配", request.getRemoteHost()));
            return "error";
        }

        LogManager.getInstance().saveLog(LogTaskFactory.getLoginSuccessTimerTask(Userinfo.getUser().getId(), user.getUsername(), request.getRemoteHost()));
        return "redirect:/";
    }

}
